package summary;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/13 15:30
 * https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/
 */
public class Title429 {

    static class Node {
        int val;
        List<Node>  children;


        public Node() {
        }

        public Node(int val) {
            this.val = val;
        }

        public Node(int val, List<Node> children) {
            this.val = val;
            this.children = children;
        }
    }

    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        LinkedList<Node> list = new LinkedList<>();
        list.offer(root);
        while (!list.isEmpty()) {
            int size = list.size();
            List<Integer> levelValue = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                Node pop = list.pop();
                levelValue.add(pop.val);
                for (Node node: pop.children) {
                    list.offer(node);
                }
            }
            result.add(levelValue);
        }
        return result;
    }




    public List<List<Integer>> levelOrder1(Node root) {
        List<List<Integer>> result = new ArrayList<>();
        dfs(root, result, 0);
        return result;
    }

    private void dfs(Node root, List<List<Integer>> result, int depth) {
        if (root == null) {
            return;
        }
        depth++;
        if (result.size() < depth) {
            List<Integer> temp = new ArrayList<>();
            result.add(temp);
        }
        result.get(depth - 1).add(root.val);
        List<Node> children = root.children;
        for (Node node : children) {
            dfs(node, result, depth);
        }
    }


    public static void main(String[] args) {

    }
}
